<template>
    <div>
        <a-cascader 
          v-model:value="cascaderValue" :options="cascderOption" @change="onChange" :fieldNames="fieldNames"
            :change-on-select="changeOnSelect" :load-data="loadData" @popup-visible-change="onPopupVisibleChange">
            <a-input v-model:value="cascaderLabel" :placeholder="placeholder" readonly>
                <template #suffix>
                    <div class="app-custom-cascader-suffix">
                        <app-dynamic-icon :iconName="cascaderPopupVisible ? 'UpOutlined' : 'DownOutlined'" />
                    </div>
                </template>
            </a-input>
        </a-cascader>
    </div>
</template>

<script setup lang="ts">
import { onMounted, PropType, ref, watch } from 'vue';

const props = defineProps({
    changeOnSelect: { //当此项为 true 时，点选每级菜单选项值都会发生变化
        type: Boolean,
        default: false
    },
    initData: {//初始化数据装载方法
        type: Function,
        default: () => { }
    },
    loadData: {//选择后的数据装载方法
        type: Function,
        default: () => { }
    },
    placeholder: {//提示
        type: String,
        default: '请选择'
    },
    label: {//文本内容
        type: String,
        default: ''
    },
    value: {//文本值
        type: Array as PropType<string[] | number[]>,
        default: () => []
    },
    labelSplitStr: {//文本内容分隔
        type: String,
        default: '/'
    },
    fieldNames: {//自定义 options 中 label name children 的字段
        type: Object as PropType<{
            label: String,
            value: String
        }>,
        default: () => {
            return {
                label: 'name',
                value: 'id'
            }
        }
    }
})

const emit = defineEmits(['update:value', 'update:label', 'change']);

const cascaderValue = ref<string[] | number[]>([]);
const cascaderLabel = ref<string>('');
const cascaderPopupVisible = ref<boolean>(false);

watch(
    [() => props.value, () => props.label],
    () => {
        cascaderValue.value = props.value;
        cascaderLabel.value = props.label;
    });


const cascderOption = ref<any[]>([]);

const loadData = (selectedOptions) => {
    props.loadData(selectedOptions, cascderOption);
}


const onChange = (value, selectedOptions) => {
    let label = '';

    selectedOptions.map((item, index) => {
        label += item[props.fieldNames.label as string] + (index < selectedOptions.length - 1 ? props.labelSplitStr : '');
    })

    cascaderLabel.value = label;

    emit('update:label', cascaderLabel.value);
    emit('update:value', cascaderValue.value);

    emit('change', {
        value: value,
        label: label,
        selectedOptions
    });

}

onMounted(() => {
    props.initData(cascderOption);
})

const onPopupVisibleChange = (value) => {
    cascaderPopupVisible.value = value;
}
</script>

<style lang="less" scoped>
.app-custom-cascader-suffix {
    font-size: 13px;
}
</style>